﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Prism.Mvvm;
using System.Windows.Media;
using System.Windows.Input;
using System.Runtime.InteropServices;
using System.Threading;
using WindowsInput;
using WindowsInput.Native;
using Prism.Commands;
using System.Windows;
using System.Windows.Interop;
using Prism.Regions;
using System.IO;
using System.Net;
using System.Net.Sockets;
using Microsoft.Win32;
using OfficeOpenXml;
using LiveCharts;
using Tryit.Views;

namespace Tryit.ViewModels
{
    public class ClientInfo : BindableBase
    {
        private string _ipAddress;
        public string IpAddress
        {
            get => _ipAddress;
            set => SetProperty(ref _ipAddress, value);
        }

        private bool _isConnected;
        public bool IsConnected
        {
            get => _isConnected;
            set => SetProperty(ref _isConnected, value);
        }

        public ClientInfo(string ipAddress)
        {
            IpAddress = ipAddress;
            IsConnected = true;
        }
    }

    public class TPAutoUploadViewModel : BindableBase, INavigationAware
    {
        private readonly SocketService _socketService;
        private readonly InputSimulator _inputSimulator;
        private const int HOTKEY_ID = 1;
        private const int MOD_ALT = 0x0001;
        private const int MOD_CONTROL = 0x0002;
        private const int MOD_SHIFT = 0x0004;
        private const int MOD_WIN = 0x0008;
        private const int VK_F2 = 0x71;
        private HwndSource _hwndSource;
        private Window _window;
        private readonly IRegionManager _regionManager;
        private bool _isHotKeyRegistered = false;

        [DllImport("user32.dll")]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);

        [DllImport("user32.dll")]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        private ICommand _autoInputCommand;
        public ICommand AutoInputCommand
        {
            get => _autoInputCommand;
            set => SetProperty(ref _autoInputCommand, value);
        }

        private ObservableCollection<PreviewDataItem> _previewData;
        public ObservableCollection<PreviewDataItem> PreviewData
        {
            get => _previewData;
            set => SetProperty(ref _previewData, value);
        }

        private ObservableCollection<string> _logMessages;
        public ObservableCollection<string> LogMessages
        {
            get => _logMessages;
            set => SetProperty(ref _logMessages, value);
        }

        private ICommand _registerHotKeyCommand;
        public ICommand RegisterHotKeyCommand
        {
            get => _registerHotKeyCommand;
            set => SetProperty(ref _registerHotKeyCommand, value);
        }

        private ICommand _unregisterHotKeyCommand;
        public ICommand UnregisterHotKeyCommand
        {
            get => _unregisterHotKeyCommand;
            set => SetProperty(ref _unregisterHotKeyCommand, value);
        }

        private bool _isServerMode = true;
        public bool IsServerMode
        {
            get => _isServerMode;
            set
            {
                if (IsServerRunning || IsClientConnected)
                {
                    MessageBox.Show("请先停止服务或断开连接后再切换模式", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                if (SetProperty(ref _isServerMode, value))
                {
                    RaisePropertyChanged(nameof(IsClientMode));
                    // 更新命令状态
                    StartServerCommand.RaiseCanExecuteChanged();
                    StopServerCommand.RaiseCanExecuteChanged();
                    ConnectCommand.RaiseCanExecuteChanged();
                    DisconnectCommand.RaiseCanExecuteChanged();
                }
            }
        }

        public bool IsClientMode
        {
            get => !_isServerMode;
            set
            {
                if (IsServerRunning || IsClientConnected)
                {
                    MessageBox.Show("请先停止服务或断开连接后再切换模式", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                IsServerMode = !value;
            }
        }

        // Server properties
        private string _localIp;
        public string LocalIp
        {
            get => _localIp;
            set => SetProperty(ref _localIp, value);
        }

        private string _port = "5000";
        public string Port
        {
            get => _port;
            set => SetProperty(ref _port, value);
        }

        private ObservableCollection<ClientInfo> _connectedClients;
        public ObservableCollection<ClientInfo> ConnectedClients
        {
            get => _connectedClients;
            set => SetProperty(ref _connectedClients, value);
        }

        private bool _isServerRunning;
        public bool IsServerRunning
        {
            get => _isServerRunning;
            set => SetProperty(ref _isServerRunning, value);
        }

        // Client properties
        private string _targetIp = "127.0.0.1";
        public string TargetIp
        {
            get => _targetIp;
            set => SetProperty(ref _targetIp, value);
        }

        private string _selectedFileName;
        public string SelectedFileName
        {
            get => _selectedFileName;
            set => SetProperty(ref _selectedFileName, value);
        }

        private string _transferStatus;
        public string TransferStatus
        {
            get => _transferStatus;
            set => SetProperty(ref _transferStatus, value);
        }

        private double _transferProgress;
        public double TransferProgress
        {
            get => _transferProgress;
            set => SetProperty(ref _transferProgress, value);
        }

        private ObservableCollection<string> _transferLogs;
        public ObservableCollection<string> TransferLogs
        {
            get => _transferLogs;
            set => SetProperty(ref _transferLogs, value);
        }

        private bool _isClientConnected;
        public bool IsClientConnected
        {
            get => _isClientConnected;
            set => SetProperty(ref _isClientConnected, value);
        }

        // Commands
        public DelegateCommand StartServerCommand { get; }
        public DelegateCommand StopServerCommand { get; }
        public DelegateCommand ConnectCommand { get; }
        public DelegateCommand DisconnectCommand { get; }
        public DelegateCommand SelectFileCommand { get; }
        public DelegateCommand SendFileCommand { get; }
        public DelegateCommand OpenCurveAnalysisCommand { get; }

        // 添加拖拽相关命令
        public DelegateCommand<PreviewDataItem> MoveItemUpCommand { get; }
        public DelegateCommand<PreviewDataItem> MoveItemDownCommand { get; }
        public DelegateCommand<PreviewDataItem> MoveItemToTopCommand { get; }
        public DelegateCommand<PreviewDataItem> MoveItemToBottomCommand { get; }

        private System.Data.DataTable _excelData;
        public System.Data.DataTable ExcelData
        {
            get => _excelData;
            set
            {
                if (_excelData != value)
                {
                    _excelData = value;
                    RaisePropertyChanged(nameof(ExcelData));
                }
            }
        }

        private ObservableCollection<string> _elements;
        private string _selectedElement;
        private SeriesCollection _seriesCollection;
        private string[] _labels;
        private Func<double, string> _yFormatter;

        public TPAutoUploadViewModel(IRegionManager regionManager)
        {
            _regionManager = regionManager;
            _inputSimulator = new InputSimulator();
            _socketService = new SocketService();
            PreviewData = new ObservableCollection<PreviewDataItem>();
            LogMessages = new ObservableCollection<string>();
            TransferLogs = new ObservableCollection<string>();
            ConnectedClients = new ObservableCollection<ClientInfo>();

            // 订阅SocketService事件
            _socketService.OnLog += message => AddLog(message);
            _socketService.OnProgress += progress => TransferProgress = progress;
            _socketService.OnStatus += status => TransferStatus = status;
            _socketService.OnFileReceived += filePath =>
            {
                SelectedFileName = filePath;
                ProcessExcelFile(filePath);
            };
            _socketService.OnClientConnected += ip =>
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    var clientInfo = new ClientInfo(ip)
                    {
                        IsConnected = true
                    };
                    ConnectedClients.Add(clientInfo);
                });
            };
            _socketService.OnClientDisconnected += ip =>
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    var client = ConnectedClients.FirstOrDefault(c => c.IpAddress == ip);
                    if (client != null)
                    {
                        ConnectedClients.Remove(client);
                    }
                });
            };

            AutoInputCommand = new DelegateCommand(ExecuteAutoInput);
            RegisterHotKeyCommand = new DelegateCommand(RegisterGlobalHotKey);
            UnregisterHotKeyCommand = new DelegateCommand(UnregisterGlobalHotKey);

            StartServerCommand = new DelegateCommand(StartServer, CanStartServer);
            StopServerCommand = new DelegateCommand(StopServer, CanStopServer);
            ConnectCommand = new DelegateCommand(async () =>
            {
                try
                {
                    await Connect();
                }
                catch (Exception ex)
                {
                    AddLog($"连接失败: {ex.Message}");
                }
            }, CanConnect);
            DisconnectCommand = new DelegateCommand(async () =>
            {
                try
                {
                    await Disconnect();
                }
                catch (Exception ex)
                {
                    AddLog($"断开连接失败: {ex.Message}");
                }
            }, CanDisconnect);
            SelectFileCommand = new DelegateCommand(SelectFile);
            SendFileCommand = new DelegateCommand(async () =>
            {
                try
                {
                    await SendFile();
                }
                catch (Exception ex)
                {
                    AddLog($"发送文件失败: {ex.Message}");
                }
            }, CanSendFile);

            // 初始化拖拽相关命令
            MoveItemUpCommand = new DelegateCommand<PreviewDataItem>(MoveItemUp, CanMoveItemUp);
            MoveItemDownCommand = new DelegateCommand<PreviewDataItem>(MoveItemDown, CanMoveItemDown);
            MoveItemToTopCommand = new DelegateCommand<PreviewDataItem>(MoveItemToTop, CanMoveItemToTop);
            MoveItemToBottomCommand = new DelegateCommand<PreviewDataItem>(MoveItemToBottom, CanMoveItemToBottom);

            GetLocalIp();
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            // 页面导航到时注册热键
            RegisterGlobalHotKey();
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            // 移除导航离开时的热键注销
        }

        private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == 0x0312) // WM_HOTKEY
            {
                if (wParam.ToInt32() == HOTKEY_ID)
                {
                    handled = true;
                    // 使用Dispatcher确保在UI线程上执行
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        ExecuteAutoInput();
                    });
                }
            }
            return IntPtr.Zero;
        }

        public void RegisterGlobalHotKey()
        {
            try
            {
                if (!_isHotKeyRegistered)
                {
                    _window = System.Windows.Application.Current.MainWindow;
                    var handle = new WindowInteropHelper(_window).Handle;

                    // 注册热键 (F2)
                    if (!RegisterHotKey(handle, HOTKEY_ID, 0, VK_F2))
                    {
                        AddLog("热键注册失败");
                        return;
                    }

                    _hwndSource = HwndSource.FromHwnd(handle);
                    _hwndSource.AddHook(HwndHook);

                    _isHotKeyRegistered = true;
                    AddLog("热键注册成功 (F2)");
                }
            }
            catch (Exception ex)
            {
                AddLog($"热键注册失败: {ex.Message}");
            }
        }

        public void UnregisterGlobalHotKey()
        {
            try
            {
                if (_isHotKeyRegistered)
                {
                    if (_window != null)
                    {
                        var handle = new WindowInteropHelper(_window).Handle;
                        UnregisterHotKey(handle, HOTKEY_ID);
                    }

                    if (_hwndSource != null)
                    {
                        _hwndSource.RemoveHook(HwndHook);
                        _hwndSource.Dispose();
                        _hwndSource = null;
                    }

                    _isHotKeyRegistered = false;
                    AddLog("热键已注销");
                }
            }
            catch (Exception ex)
            {
                AddLog($"热键注销失败: {ex.Message}");
            }
        }

        private void AddLog(string message)
        {
            Application.Current.Dispatcher.BeginInvoke(new Action(() =>
            {
                LogMessages.Insert(0, $"[{DateTime.Now:HH:mm:ss.fff}] {message}");
                if (LogMessages.Count > 100) // 限制日志条数
                {
                    LogMessages.RemoveAt(LogMessages.Count - 1);
                }
            }));
        }

        private void ExecuteAutoInput()
        {
            // 首先检查数据是否都在范围内
            var outOfRangeItems = PreviewData.Where(item => item.Status == "×").ToList();
            if (outOfRangeItems.Any())
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    var message = "以下数据超出范围：\n" + string.Join("\n", outOfRangeItems.Select(item => $"{item.Text} (范围: {item.Range})"));
                    MessageBox.Show(message, "数据超出范围", MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK, MessageBoxOptions.ServiceNotification);
                });
                return;
            }

            // 找到第一个未完成的数据组
            var currentGroup = new List<PreviewDataItem>();
            bool foundGroup = false;

            // 查找第一个未完成的数据组
            for (int i = 0; i < PreviewData.Count; i++)
            {
                if (PreviewData[i].Status == "未完成" && !foundGroup)
                {
                    foundGroup = true;
                    currentGroup.Add(PreviewData[i]);
                }
                else if (foundGroup)
                {
                    // 如果遇到分隔线，则结束当前组
                    if (PreviewData[i].Text == "----------------------------------------")
                    {
                        break;
                    }
                    // 否则继续添加到当前组
                    currentGroup.Add(PreviewData[i]);
                }
            }

            if (!currentGroup.Any())
            {
                AddLog("所有数据组都已完成");
                return;
            }

            Task.Run(() =>
            {
                AddLog("开始执行自动输入...");
                // 等待3秒，让用户切换到目标窗口
                Thread.Sleep(3000);

                int count = 0;
                foreach (var item in currentGroup)
                {
                    try
                    {
                        count++;
                        AddLog($"正在处理第 {count} 个数据: {item.Text}");

                        // 提取数值部分
                        var value = item.Text.Split('：')[1].Replace("%", "");

                        // 输入数值
                        _inputSimulator.Keyboard.TextEntry(value);
                        AddLog($"输入数值: {value}");
                        Thread.Sleep(300); // 增加输入后的等待时间

                        // 按Tab键
                        _inputSimulator.Keyboard.KeyPress(VirtualKeyCode.TAB);
                        AddLog($"按下Tab键");
                        Thread.Sleep(500); // 增加Tab键后的等待时间
                        if (count == 1)
                        {
                            for (int i = 0; i < 6; i++)
                            {
                                // 按Tab键
                                _inputSimulator.Keyboard.KeyPress(VirtualKeyCode.TAB);
                                AddLog($"按下Tab键");
                                Thread.Sleep(300); // 增加Tab键后的等待时间
                            }
                        }//跳过第一行标题 
                    }
                    catch (Exception ex)
                    {
                        AddLog($"输入错误: {ex.Message}");
                        System.Diagnostics.Debug.WriteLine($"输入错误: {ex.Message}");
                    }
                }

                // 更新当前组的状态
                Application.Current.Dispatcher.Invoke(() =>
                {
                    foreach (var item in currentGroup)
                    {
                        if (item.Status == "未完成")
                        {
                            item.Status = "Finished";
                            item.StatusColor = new SolidColorBrush(Colors.Green);
                        }
                    }
                });

                AddLog("自动输入完成");
            });
        }

        public class PreviewDataItem : BindableBase
        {
            private string _text;
            public string Text
            {
                get => _text;
                set => SetProperty(ref _text, value);
            }

            private string _range;
            public string Range
            {
                get => _range;
                set => SetProperty(ref _range, value);
            }

            private string _status;
            public string Status
            {
                get => _status;
                set => SetProperty(ref _status, value);
            }

            private Brush _textColor;
            public Brush TextColor
            {
                get => _textColor;
                set => SetProperty(ref _textColor, value);
            }

            private Brush _statusColor;
            public Brush StatusColor
            {
                get => _statusColor;
                set => SetProperty(ref _statusColor, value);
            }

            // 添加拖拽相关属性
            private bool _isDragging;
            public bool IsDragging
            {
                get => _isDragging;
                set => SetProperty(ref _isDragging, value);
            }

            private bool _isDragOver;
            public bool IsDragOver
            {
                get => _isDragOver;
                set => SetProperty(ref _isDragOver, value);
            }

            // 添加排序索引
            private int _sortIndex;
            public int SortIndex
            {
                get => _sortIndex;
                set => SetProperty(ref _sortIndex, value);
            }

            // 添加是否可拖拽属性
            private bool _canDrag = true;
            public bool CanDrag
            {
                get => _canDrag;
                set => SetProperty(ref _canDrag, value);
            }
        }

        private Dictionary<string, (double min, double max)> elementRanges = new Dictionary<string, (double min, double max)>
        {
            {"Si", (6.5, 7.5)},
            {"Mn", (0.0, 0.05)},
            {"Cu", (0.0, 0.05)},
            {"Zn", (0.0, 0.05)},
            {"Ni", (0.0, 0.05)},
            {"Pb", (0.0, 0.05)},
            {"Sn", (0.0, 0.05)},
            {"Ca", (0.0, 0.05)},
            {"Cr", (0.0, 0.05)},
            {"Fe", (0.0, 0.12)},
            {"Mg", (0.25, 0.45)},
            {"Ti", (0.08, 0.2)}
        };

        public void UpdatePreviewData(System.Data.DataTable dataTable)
        {
            string[] lunum = dataTable.TableName.Split("-");

            // 不要清除现有数据，而是追加新数据
            if (dataTable != null && dataTable.Rows.Count >= 2)
            {
                int currentIndex = PreviewData.Count;

                // 添加文件名作为分隔
                PreviewData.Add(new PreviewDataItem
                {
                    Text = $"炉号：{lunum[2] + "-" + lunum[3].PadLeft(2, '0')}",
                    Range = "",
                    Status = "未完成",
                    TextColor = new SolidColorBrush(Colors.Blue),
                    StatusColor = new SolidColorBrush(Colors.Blue),
                    SortIndex = currentIndex++,
                    CanDrag = false // 炉号不可拖拽
                });

                // 定义显示顺序
                string[] displayOrder = new string[]
                {
                    "Si", "Mn", "Cu", "Zn", "Ni", "Pb", "Sn", "Ca", "Cr"
                };

                // 创建元素值字典
                Dictionary<string, string> elementValues = new Dictionary<string, string>();
                for (int col = 0; col < dataTable.Columns.Count; col++)
                {
                    var element = dataTable.Rows[0][col].ToString().Trim();
                    var value = dataTable.Rows[1][col].ToString().Trim();
                    if (!string.IsNullOrEmpty(element) && !string.IsNullOrEmpty(value))
                    {
                        value = value.Replace("%", "");
                        elementValues[element] = value;
                    }
                }

                // 按顺序添加元素
                foreach (var element in displayOrder)
                {
                    if (elementValues.ContainsKey(element))
                    {
                        var value = elementValues[element];
                        var range = elementRanges.ContainsKey(element) ? elementRanges[element] : (0.0, 0.0);
                        var isInRange = IsValueInRange(value, range.Item1, range.Item2);

                        PreviewData.Add(new PreviewDataItem
                        {
                            Text = $"{element}：{value}%",
                            Range = range.Item1 == 0 ? $"≤{range.Item2:F2}%" : $"{range.Item1:F2}~{range.Item2:F2}%",
                            Status = isInRange ? "✓" : "×",
                            TextColor = isInRange ? new SolidColorBrush(Colors.Green) : new SolidColorBrush(Colors.Red),
                            StatusColor = isInRange ? new SolidColorBrush(Colors.Green) : new SolidColorBrush(Colors.Red),
                            SortIndex = currentIndex++
                        });
                    }
                }

                // 添加剩余元素
                string[] remainingElements = new string[] { "Fe", "Mg", "Ti" };
                foreach (var element in remainingElements)
                {
                    if (elementValues.ContainsKey(element))
                    {
                        var value = elementValues[element];
                        var range = elementRanges.ContainsKey(element) ? elementRanges[element] : (0.0, 0.0);
                        var isInRange = IsValueInRange(value, range.Item1, range.Item2);

                        PreviewData.Add(new PreviewDataItem
                        {
                            Text = $"{element}：{value}%",
                            Range = range.Item1 == 0 ? $"≤{range.Item2:F2}%" : $"{range.Item1:F2}~{range.Item2:F2}%",
                            Status = isInRange ? "✓" : "×",
                            TextColor = isInRange ? new SolidColorBrush(Colors.Green) : new SolidColorBrush(Colors.Red),
                            StatusColor = isInRange ? new SolidColorBrush(Colors.Green) : new SolidColorBrush(Colors.Red),
                            SortIndex = currentIndex++
                        });
                    }
                }
                    // 添加其它杂质总和
                PreviewData.Add(new PreviewDataItem
                {
                    Text = "其它杂质总和：0.05%",
                    Range = "≤0.15%",
                    Status = "✓",
                    TextColor = new SolidColorBrush(Colors.Green),
                    StatusColor = new SolidColorBrush(Colors.Green),
                    SortIndex = currentIndex++
                });
                                // 添加其它杂质每种
                PreviewData.Add(new PreviewDataItem
                {
                    Text = "其它杂质每种：0.001%",
                    Range = "≤0.05%",
                    Status = "✓",
                    TextColor = new SolidColorBrush(Colors.Green),
                    StatusColor = new SolidColorBrush(Colors.Green),
                    SortIndex = currentIndex++
                });

                // 添加分隔线
                PreviewData.Add(new PreviewDataItem
                {
                    Text = "----------------------------------------",
                    Range = "",
                    Status = "",
                    TextColor = new SolidColorBrush(Colors.Gray),
                    StatusColor = new SolidColorBrush(Colors.Gray),
                    SortIndex = currentIndex++,
                    CanDrag = false // 分隔线不可拖拽
                });
            }
        }

        private bool IsValueInRange(string valueStr, double min, double max)
        {
            if (double.TryParse(valueStr, out double value))
            {
                return value >= min && value <= max;
            }
            return false;
        }


        private void GetLocalIp()
        {
            try
            {
                var host = Dns.GetHostEntry(Dns.GetHostName());
                foreach (var ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        LocalIp = ip.ToString();
                        break;
                    }
                }

                if (string.IsNullOrEmpty(LocalIp))
                {
                    LocalIp = "127.0.0.1";
                    AddLog("无法获取本机IP，使用默认IP: 127.0.0.1");
                }
                else
                {
                    AddLog($"本机IP: {LocalIp}");
                }
            }
            catch (Exception ex)
            {
                LocalIp = "127.0.0.1";
                AddLog($"获取本机IP失败: {ex.Message}，使用默认IP: 127.0.0.1");
            }
        }

        private bool CanStartServer()
        {
            return !IsServerRunning && IsServerMode && !string.IsNullOrEmpty(Port);
        }

        private async void StartServer()
        {
            try
            {
                if (int.TryParse(Port, out int port))
                {
                    IsServerRunning = true;
                    AddLog($"正在启动服务器，监听端口: {port}");
                    await _socketService.StartServer(port);
                }
                else
                {
                    AddLog("端口号格式无效");
                    IsServerRunning = false;
                }
            }
            catch (Exception ex)
            {
                AddLog($"启动服务器失败: {ex.Message}");
                IsServerRunning = false;
            }
        }

        private bool CanStopServer()
        {
            return IsServerRunning && IsServerMode;
        }

        private void StopServer()
        {
            try
            {
                _socketService.StopServer();
                IsServerRunning = false;
                ConnectedClients.Clear();
                AddLog("服务器已停止");
            }
            catch (Exception ex)
            {
                AddLog($"停止服务器失败: {ex.Message}");
                IsServerRunning = true;
            }
        }

        private bool CanConnect()
        {
            return !IsClientConnected && IsClientMode && !string.IsNullOrEmpty(TargetIp) && !string.IsNullOrEmpty(Port);
        }

        private bool CanDisconnect()
        {
            return IsClientConnected && IsClientMode;
        }

        private async Task Connect()
        {
            try
            {
                if (int.TryParse(Port, out int port))
                {
                    await _socketService.Connect(TargetIp, port);
                    IsClientConnected = true;
                }
                else
                {
                    AddLog("端口号格式无效");
                }
            }
            catch (Exception ex)
            {
                AddLog($"连接失败: {ex.Message}");
            }
        }

        private async Task Disconnect()
        {
            try
            {
                _socketService.Disconnect();
                IsClientConnected = false;
            }
            catch (Exception ex)
            {
                AddLog($"断开连接失败: {ex.Message}");
            }
        }

        private void SelectFile()
        {
            var dialog = new OpenFileDialog();
            if (dialog.ShowDialog() == true)
            {
                SelectedFileName = dialog.FileName;
                if (IsServerMode)
                {
                    SendFileToAllClients();
                }
                else if (IsClientMode && IsClientConnected)
                {
                    SendFile();
                }
            }
        }

        private bool CanSendFile()
        {
            return IsClientConnected && !string.IsNullOrEmpty(SelectedFileName) && IsClientMode;
        }

        private async Task SendFile()
        {
            try
            {
                if (!string.IsNullOrEmpty(SelectedFileName) && File.Exists(SelectedFileName))
                {
                    await _socketService.SendFileAsync(SelectedFileName);

                }
                else
                {
                    AddLog("请选择有效的文件");
                }
            }
            catch (Exception ex)
            {
                AddLog($"发送文件失败: {ex.Message}");
            }
        }

        private async void SendFileToAllClients()
        {
            if (string.IsNullOrEmpty(SelectedFileName) || !File.Exists(SelectedFileName))
            {
                AddLog("请选择有效的文件");
                return;
            }

            try
            {
                await _socketService.SendFileAsync(SelectedFileName);

            }
            catch (Exception ex)
            {
                AddLog($"发送文件失败: {ex.Message}");
            }
        }

        private void ProcessExcelFile(string filePath)
        {
            try
            {
                // 检查文件是否存在
                if (!File.Exists(filePath))
                {
                    throw new FileNotFoundException("找不到指定的文件。", filePath);
                }

                // 检查文件访问权限
                try
                {
                    using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        // 如果能打开文件，说明有访问权限
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    throw new UnauthorizedAccessException("无法访问文件，请检查文件权限或以管理员身份运行程序。");
                }

                using (var package = new ExcelPackage(new FileInfo(filePath)))
                {
                    var workbook = package.Workbook;
                    if (workbook.Worksheets.Count == 0)
                    {
                        throw new Exception("Excel文件中没有工作表。");
                    }

                    var worksheet = workbook.Worksheets[0];
                    if (worksheet.Dimension == null)
                    {
                        throw new Exception("工作表是空的。");
                    }

                    var endRow = worksheet.Dimension.End.Row;
                    var endColumn = worksheet.Dimension.End.Column;

                    if (endRow < 2)
                    {
                        throw new Exception("Excel文件中数据行数不足。");
                    }

                    // 创建数据表来存储Excel数据
                    var dataTable = new System.Data.DataTable();

                    // 添加列
                    for (int col = 1; col <= endColumn; col++)
                    {
                        var columnName = worksheet.Cells[1, col].Text;
                        if (string.IsNullOrEmpty(columnName))
                            columnName = $"Column {col}";

                        // 检查列名是否已存在
                        if (dataTable.Columns.Contains(columnName))
                        {
                            columnName = $"{columnName}_{col}";
                        }

                        dataTable.Columns.Add(columnName);
                    }

                    // 添加数据行
                    for (int row = 2; row <= endRow; row++)
                    {
                        var dataRow = dataTable.NewRow();
                        for (int col = 1; col <= endColumn; col++)
                        {
                            dataRow[col - 1] = worksheet.Cells[row, col].Text;
                        }
                        dataTable.Rows.Add(dataRow);
                    }

                    // 在UI线程上更新数据
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        // 更新预览数据
                        UpdatePreviewData(dataTable);
                        // 设置ExcelData属性以绑定到DataGrid
                        ExcelData = dataTable;
                        AddLog("Excel文件处理完成");
                    });
                }
            }
            catch (FileNotFoundException ex)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    AddLog($"文件不存在: {ex.Message}");
                });
            }
            catch (UnauthorizedAccessException ex)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    AddLog(ex.Message);
                    MessageBox.Show(ex.Message, "访问权限错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                });
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    AddLog($"处理Excel文件失败: {ex.Message}");
                });
            }
        }

        // 拖拽相关方法
        private bool CanMoveItemUp(PreviewDataItem item)
        {
            if (item == null || !item.CanDrag) return false;
            int index = PreviewData.IndexOf(item);
            return index > 0 && PreviewData[index - 1].CanDrag;
        }

        private bool CanMoveItemDown(PreviewDataItem item)
        {
            if (item == null || !item.CanDrag) return false;
            int index = PreviewData.IndexOf(item);
            return index < PreviewData.Count - 1 && PreviewData[index + 1].CanDrag;
        }

        private bool CanMoveItemToTop(PreviewDataItem item)
        {
            if (item == null || !item.CanDrag) return false;
            int index = PreviewData.IndexOf(item);
            return index > 0;
        }

        private bool CanMoveItemToBottom(PreviewDataItem item)
        {
            if (item == null || !item.CanDrag) return false;
            int index = PreviewData.IndexOf(item);
            return index < PreviewData.Count - 1;
        }

        private void MoveItemUp(PreviewDataItem item)
        {
            if (!CanMoveItemUp(item)) return;
            
            int index = PreviewData.IndexOf(item);
            PreviewData.Move(index, index - 1);
            UpdateSortIndexes();
        }

        private void MoveItemDown(PreviewDataItem item)
        {
            if (!CanMoveItemDown(item)) return;
            
            int index = PreviewData.IndexOf(item);
            PreviewData.Move(index, index + 1);
            UpdateSortIndexes();
        }

        private void MoveItemToTop(PreviewDataItem item)
        {
            if (!CanMoveItemToTop(item)) return;
            
            int index = PreviewData.IndexOf(item);
            PreviewData.Move(index, 0);
            UpdateSortIndexes();
        }

        private void MoveItemToBottom(PreviewDataItem item)
        {
            if (!CanMoveItemToBottom(item)) return;
            
            int index = PreviewData.IndexOf(item);
            PreviewData.Move(index, PreviewData.Count - 1);
            UpdateSortIndexes();
        }

        private void UpdateSortIndexes()
        {
            for (int i = 0; i < PreviewData.Count; i++)
            {
                PreviewData[i].SortIndex = i;
            }
        }

        // 拖拽排序方法
        public void MoveItem(int fromIndex, int toIndex)
        {
            if (fromIndex < 0 || fromIndex >= PreviewData.Count || 
                toIndex < 0 || toIndex >= PreviewData.Count) return;
            
            if (!PreviewData[fromIndex].CanDrag) return;
            
            PreviewData.Move(fromIndex, toIndex);
            UpdateSortIndexes();
        }
    }

    public class SocketService
    {
        private Socket _serverSocket;
        private Socket _clientSocket;
        private readonly int _bufferSize = 8192;
        private readonly string _saveDirectory;
        private readonly List<Socket> _connectedClients = new List<Socket>();

        public event Action<string> OnLog;
        public event Action<double> OnProgress;
        public event Action<string> OnStatus;
        public event Action<string> OnFileReceived;
        public event Action<string> OnClientConnected;
        public event Action<string> OnClientDisconnected;

        public SocketService()
        {
            _saveDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "ReceivedFiles");
            if (!Directory.Exists(_saveDirectory))
            {
                Directory.CreateDirectory(_saveDirectory);
            }
        }

        public async Task StartServer(int port)
        {
            try
            {
                if (_serverSocket != null)
                {
                    _serverSocket.Close();
                    _serverSocket = null;
                }

                _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _serverSocket.Bind(new IPEndPoint(IPAddress.Any, port));
                _serverSocket.Listen(10);

                // 启动一个后台任务来处理客户端连接
                _ = Task.Run(async () =>
                {
                    while (_serverSocket != null)
                    {
                        try
                        {
                            var clientSocket = await _serverSocket.AcceptAsync();
                            _connectedClients.Add(clientSocket);
                            var remoteEndPoint = (IPEndPoint)clientSocket.RemoteEndPoint;
                            OnClientConnected?.Invoke(remoteEndPoint.Address.ToString());
                            _ = HandleClientAsync(clientSocket);
                        }
                        catch (ObjectDisposedException)
                        {
                            break;
                        }
                        catch (Exception ex)
                        {
                            OnLog?.Invoke($"接受客户端连接时出错: {ex.Message}");
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                OnLog?.Invoke($"服务器启动失败: {ex.Message}");
                throw;
            }
        }

        public void StopServer()
        {
            try
            {
                if (_serverSocket != null)
                {
                    _serverSocket.Close();
                    _serverSocket = null;
                }

                foreach (var client in _connectedClients.ToList())
                {
                    try
                    {
                        client.Close();
                    }
                    catch { }
                }
                _connectedClients.Clear();

                OnLog?.Invoke("服务器已停止");
            }
            catch (Exception ex)
            {
                OnLog?.Invoke($"停止服务器时出错: {ex.Message}");
                throw;
            }
        }

        public async Task Connect(string ip, int port)
        {
            try
            {
                _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                await _clientSocket.ConnectAsync(new IPEndPoint(IPAddress.Parse(ip), port));
                OnLog?.Invoke($"已连接到服务器 {ip}:{port}");
                _ = ReceiveFilesAsync();
            }
            catch (Exception ex)
            {
                OnLog?.Invoke($"连接失败: {ex.Message}");
            }
        }

        public void Disconnect()
        {
            try
            {
                _clientSocket?.Close();
                _clientSocket = null;
                OnLog?.Invoke("已断开连接");
            }
            catch (Exception ex)
            {
                OnLog?.Invoke($"断开连接失败: {ex.Message}");
            }
        }

        private async Task HandleClientAsync(Socket clientSocket)
        {
            try
            {
                var remoteEndPoint = (IPEndPoint)clientSocket.RemoteEndPoint;
                OnLog?.Invoke($"客户端已连接: {remoteEndPoint.Address}");

                while (true)
                {
                    try
                    {
                        if (!clientSocket.Connected)
                        {
                            break;
                        }

                        if (clientSocket.Available > 0)
                        {
                            await ReceiveFileAsync(clientSocket);
                        }

                        // 检查连接是否仍然有效
                        bool isConnected = !(clientSocket.Poll(1, SelectMode.SelectRead) && clientSocket.Available == 0);
                        if (!isConnected)
                        {
                            break;
                        }

                        await Task.Delay(100);
                    }
                    catch (SocketException)
                    {
                        break;
                    }
                    catch (ObjectDisposedException)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                OnLog?.Invoke($"处理客户端时出错: {ex.Message}");
            }
            finally
            {
                try
                {
                    var remoteEndPoint = (IPEndPoint)clientSocket.RemoteEndPoint;
                    _connectedClients.Remove(clientSocket);
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        OnClientDisconnected?.Invoke(remoteEndPoint.Address.ToString());
                    });
                    clientSocket.Close();
                }
                catch (Exception ex)
                {
                    OnLog?.Invoke($"清理客户端连接时出错: {ex.Message}");
                }
            }
        }

        private async Task ReceiveFileAsync(Socket socket)
        {
            try
            {
                // 接收文件名长度
                var fileNameLengthBytes = new byte[4];
                await socket.ReceiveAsync(fileNameLengthBytes, SocketFlags.None);
                int fileNameLength = BitConverter.ToInt32(fileNameLengthBytes, 0);

                // 接收文件名
                var fileNameBytes = new byte[fileNameLength];
                int received = 0;
                while (received < fileNameLength)
                {
                    int bytesRead = await socket.ReceiveAsync(new ArraySegment<byte>(fileNameBytes, received, fileNameLength - received), SocketFlags.None);
                    received += bytesRead;
                }
                var fileName = Encoding.UTF8.GetString(fileNameBytes);

                // 接收文件大小
                var fileSizeBytes = new byte[8];
                received = 0;
                while (received < 8)
                {
                    int bytesRead = await socket.ReceiveAsync(new ArraySegment<byte>(fileSizeBytes, received, 8 - received), SocketFlags.None);
                    received += bytesRead;
                }
                var fileSize = BitConverter.ToInt64(fileSizeBytes, 0);

                var savePath = Path.Combine(_saveDirectory, fileName);
                OnLog?.Invoke($"开始接收文件: {fileName} ({fileSize} bytes)");
                OnLog?.Invoke($"文件将保存到: {savePath}");
                OnStatus?.Invoke($"正在接收: {fileName}");
                OnProgress?.Invoke(0);

                using (var fileStream = File.Create(savePath))
                {
                    var buffer = new byte[_bufferSize];
                    long bytesReceived = 0;

                    while (bytesReceived < fileSize)
                    {
                        var bytesToRead = Math.Min(_bufferSize, fileSize - bytesReceived);
                        var bytesRead = await socket.ReceiveAsync(new ArraySegment<byte>(buffer, 0, (int)bytesToRead), SocketFlags.None);
                        await fileStream.WriteAsync(buffer, 0, bytesRead);
                        bytesReceived += bytesRead;

                        var progress = (double)bytesReceived / fileSize * 100;
                        OnProgress?.Invoke(progress);
                        OnStatus?.Invoke($"正在接收: {progress:F1}%");
                    }
                }

                // 发送接收完成确认
                var response = Encoding.UTF8.GetBytes("RECEIVED");
                await socket.SendAsync(response, SocketFlags.None);

                OnLog?.Invoke($"文件已成功接收并保存到: {savePath}");
                OnStatus?.Invoke("文件接收完成");
                OnProgress?.Invoke(100);
                OnFileReceived?.Invoke(savePath);
            }
            catch (Exception ex)
            {
                OnLog?.Invoke($"接收文件时出错: {ex.Message}");
            }
        }

        private async Task ReceiveFilesAsync()
        {
            try
            {
                while (_clientSocket != null && _clientSocket.Connected)
                {
                    if (_clientSocket.Available > 0)
                    {
                        await ReceiveFileAsync(_clientSocket);
                    }
                    await Task.Delay(100);
                }
            }
            catch (Exception ex)
            {
                OnLog?.Invoke($"接收文件线程出错: {ex.Message}");
            }
        }

        public async Task SendFileAsync(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                {
                    OnLog?.Invoke("文件不存在");
                    return;
                }

                var fileName = Path.GetFileName(filePath);
                var fileSize = new FileInfo(filePath).Length;

                if (_clientSocket != null)
                {
                    // 客户端模式发送文件
                    await SendFileToSocket(_clientSocket, filePath, fileName, fileSize);
                }
                else if (_connectedClients.Count > 0)
                {
                    // 服务端模式发送文件到所有客户端
                    foreach (var clientSocket in _connectedClients.ToList())
                    {
                        if (clientSocket.Connected)
                        {
                            try
                            {
                                await SendFileToSocket(clientSocket, filePath, fileName, fileSize);
                            }
                            catch (Exception ex)
                            {
                                OnLog?.Invoke($"发送文件到客户端失败: {ex.Message}");
                                _connectedClients.Remove(clientSocket);
                            }
                        }
                        else
                        {
                            _connectedClients.Remove(clientSocket);
                        }
                    }
                }
                else
                {
                    OnLog?.Invoke("没有可用的连接");
                }
            }
            catch (Exception ex)
            {
                OnLog?.Invoke($"发送文件失败: {ex.Message}");
            }
        }

        private async Task SendFileToSocket(Socket socket, string filePath, string fileName, long fileSize)
        {
            // 发送文件名长度
            var fileNameBytes = Encoding.UTF8.GetBytes(fileName);
            var fileNameLengthBytes = BitConverter.GetBytes(fileNameBytes.Length);
            await socket.SendAsync(fileNameLengthBytes, SocketFlags.None);

            // 发送文件名
            await socket.SendAsync(fileNameBytes, SocketFlags.None);

            // 发送文件大小
            var fileSizeBytes = BitConverter.GetBytes(fileSize);
            await socket.SendAsync(fileSizeBytes, SocketFlags.None);

            OnLog?.Invoke($"开始发送文件: {fileName}");
            OnStatus?.Invoke($"正在发送: {fileName}");
            OnProgress?.Invoke(0);

            using (var fileStream = File.OpenRead(filePath))
            {
                var buffer = new byte[_bufferSize];
                long bytesSent = 0;
                int bytesRead;

                while ((bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    await socket.SendAsync(new ArraySegment<byte>(buffer, 0, bytesRead), SocketFlags.None);
                    bytesSent += bytesRead;
                    var progress = (double)bytesSent / fileSize * 100;
                    OnProgress?.Invoke(progress);
                    OnStatus?.Invoke($"正在发送: {progress:F1}%");
                }
            }

            // 等待接收完成确认
            var responseBuffer = new byte[8];
            int responseReceived = 0;
            while (responseReceived < 8)
            {
                int bytesRead = await socket.ReceiveAsync(new ArraySegment<byte>(responseBuffer, responseReceived, 8 - responseReceived), SocketFlags.None);
                responseReceived += bytesRead;
            }
            var response = Encoding.UTF8.GetString(responseBuffer).TrimEnd('\0');

            if (response == "RECEIVED")
            {
                OnLog?.Invoke($"文件已成功发送: {fileName}");
                OnStatus?.Invoke("文件发送完成");
                OnProgress?.Invoke(100);
            }
            else
            {
                throw new Exception("接收方未确认接收完成");
            }
        }
    }
}


